Ext.ns('ru.proburo.oms.order.components');

/**
 * ru.proburo.oms.order.components.List
 * @extends ru.proburo.oms.components.grid.AbstractList
 */
ru.proburo.oms.order.components.List = Ext.extend(ru.proburo.oms.components.grid.AbstractList, {
	
    constructor: function(config)
	{
		config = config || {};
        
		this.store = new ru.proburo.oms.order.dao.OrderStore({storeId: 'order-store'});
		
        ru.proburo.oms.order.components.List.superclass.constructor.call(this, config);
    },
	
	initTBar: function()
	{
		this.addAction = new Ext.Action({
			text: 	 'Создать',
			tooltip: 'Создать новый заказ',
			iconCls: 'silk-table-add',
			handler: this._doAdd,
			scope: 	 this
		});
		this.openAction = new Ext.Action({
			text: 	  'Редактировать',
			iconCls:  'silk-table-edit',
			disabled: true,			
			handler:  this._doOpen,
			scope:    this
		});
		
		this.deleteAction = new Ext.Action({
			text: 	  'Удалить',
			tooltip:  'Удалить выделенные заказы',
			iconCls:  'silk-table-delete',
			disabled: true,			
			handler:  this._doDelete,
			scope:    this
		});
		
		this.importAction = new Ext.Action({
			text: 	   'Импорт',
			tooltip:   'Импортировать заказ',
			iconCls:   'silk-table-go',
			disabled:  false,
			handler:   this._doImport,
			scope:	   this
		});
		this.exportAction = new Ext.Action({
			text: 	  'Экспорт',
			tooltip:  'Экспортировать заказ',
			iconCls:  'silk-table-go',
			disabled: true,		
			handler:  this._doExport,
			scope:    this
		});
		
		if(Ext.isAir){
			return [
				this.addAction,
				this.openAction,
				this.deleteAction,
				'->',
				this.exportAction
			];
		}
		else
		{
			return [
				this.addAction,
				this.openAction,
				this.deleteAction,
				'->',
				this.importAction
			];
		}
	},
	
	initColumns: function()
	{
		if(true === Ext.isAir)
		{
			return [
				{
					id: 	   'id',
					header:    '№',
					dataIndex: 'id',
					width: 	   20
				},
				{
					id: 	   'address',
					header:    'Адрес доставки',
					dataIndex: 'address',
					width: 	   150
				},
				{
					id: 	   'contact_person',
					header:    'Контактное лицо',
					dataIndex: 'contact_person',
					width: 	   150
				},
				{
					id: 	   'phone',
					header:    'Контактный телефон',
					dataIndex: 'phone',
					width: 	   60
				},
				{
					id: 	   'summ',
					header:    'Сумма, руб.',
					dataIndex: 'summ',
					width:     50,
					renderer:  Ext.util.Format.ruMoney
				}
			];
			
		}
		else
		{
			return [
				{
					header:    '№',
					dataIndex: 'id',
					width: 	   95
				},
				{
					header:    'Подразделение',
					dataIndex: 'department',
					width: 	   300
				},
				{
					header:    'Юр. лицо',
					dataIndex: 'customer',
					width: 	   300
				},
				{
					header:    'Контактное лицо',
					dataIndex: 'contact_person',
					width: 	   110
				},
				{
					header:    'Контактный телефон',
					dataIndex: 'phone',
					width: 	   130
				},
				{
					header:    'Отправлен',
					dataIndex: 'submit_date',
					width: 	   100,
					renderer:  this._dateRenderer
				},
				{
					header:    'Сумма, руб.',
					dataIndex: 'summ',
					width:     100,
					renderer:  Ext.util.Format.ruMoney
				}
			];
		}
	},
	
	initEvents: function()
	{		
		ru.proburo.oms.order.components.List.superclass.initEvents.call(this);
		
        this.getSelectionModel().on('selectionchange', this._onSelectionChange, this);
		
		if(this.tree)
		{
			this.origTitle = this.title;
			
			this.tree.on('click', this._onClick, this);
			
			this.tree.getRootNode().on('expand', this._onRootNodeExpand, this, {single: true});
		}
	},
	
	/**
	 * Action handlers
	 */
	// private
	_doAdd: function(b, e)
	{
		var record = this.activator._createOrder();
		
		this.activator._openOrder(record);
	},
	
	// private
	_doOpen: function(b, e)
	{
		var record = this.getSelectionModel().getSelected();
		
		this.activator._openOrder(record);
	},
	
	// private
	_doDelete: function(b, e)
	{
		var store   = this.getStore();
		var sm      = this.getSelectionModel();
		var records = sm.getSelections();
		
		for(var i in records)
		{
			if(store.indexOf(records[i]) != -1)
			{
				store.remove(records[i]);
			}
		}
		
		sm.clearSelections();
		
		store.save();
	},
	
	// private
	_doImport: function(b, e)
	{
		this.importAction.setDisabled(true);
		
		var dlg = new ru.proburo.oms.order.components['import'].Dialog();
		dlg.on({
			'complete': function(dialog, order, items){		
				this.activator._createFuckinOrder(order, items);
				dialog.close();
			},
			'exception': function(dialog, exception){		
				throw exception;
				dialog.close();
			},
			'close': function()
			{
				this.importAction.setDisabled(false);
			},
			scope: this
		});
		dlg.show();
	},
	
	// private
	_doExport: function(b, e)
	{
		var record = this.getSelectionModel().getSelected();
		var store =  new ru.proburo.oms.order.dao.OrderLineStore();
		store.setOrderID(record.data.id);
		store.load();
		store.on('load', function(){
			var exporter = new ru.proburo.oms.components.Exporter();
			exporter.save(record, store, 'csv');
		}, this);
	},
	
	
	/**
	 * Listeners
	 */
	// private
	_onClick: function(node, event)
	{
		var title  = node.attributes.text;
		var status = node.attributes.status;
		
		if(typeof(status) != 'undefined' && status != this.currentStatus)
		{
			if(true === Ext.isAir)
			{
				if(-1 !== status)
				{
					this.store.setBaseParam('where', ' WHERE status='+status);
				}
				else
				{
					this.store.setBaseParam('where', '');
				}
			}
			else
			{
				this.store.setBaseParam('status', status);
			}
			
			this.store.load();
			this.currentStatus = status;
		}
		
		this.setTitle(this.origTitle + ': ' + title);
		
		var panel = this.activator.panel;
		var key   = panel.items.getKey(this);
		panel.setActiveTab(key);
	},
	
	// private
	_onRootNodeExpand: function(rootNode)
	{
		console.log('_onRootNodeExpand()');
		
		var child = rootNode.firstChild;
		
		this.tree.selectPath(child.getPath());
		
		child.fireEvent('click', child);
	},
	
	// private
	_onSelectionChange: function(sm)
	{
		var editable = true;
		var disabled = !sm.getCount();
		
		Ext.each(sm.getSelections(), function(r){
			if(r.data.status == 10){
				editable = false;
			}
		}, this);
		
		if(false === disabled)
		{
			if(false === editable)
			{
				this.openAction.setText('Просмотреть');
				this.openAction.setIconClass('silk-table');
			}
			else
			{
				this.openAction.setText('Редактировать');
				this.openAction.setIconClass('silk-table-edit');
			}
		}
		
		this.openAction.setDisabled(disabled);
		this.deleteAction.setDisabled(disabled || !editable);
		this.exportAction.setDisabled(disabled);
	},
	
	
	
	
	
	
	
	
	
	/**
     * Renderers
     */
	// private
	_dateRenderer: function(v, params, data)
	{
		return (v && v.dateFormat && v.valueOf() > 0) ? v.dateFormat("d.m.Y H:i:s") : '';
	},
	// private
	_idRenderer: function(v, params, data)
	{
		return (App.data.orders.getById(v) && (fid = App.data.orders.getById(v).get('foreign_id'))) ? fid : v;
	}
});